#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
练习题 41: 设计模式组合器
难度: ⭐⭐⭐
知识点: 设计模式组合、架构设计、面向对象高级特性
参考文件: design_patterns/ 目录下的所有文件
"""

from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Callable
import threading
import time
from enum import Enum

def problem_description():
    """
    题目描述:
    设计一个设计模式组合器系统，能够将多种设计模式有机结合，
    创建复杂的软件架构解决方案。
    
    要求:
    1. 实现单例+工厂模式组合
    2. 实现观察者+命令模式组合
    3. 实现策略+装饰器模式组合
    4. 实现建造者+原型模式组合
    5. 设计模式注册和发现机制
    
    应用场景:
    - 配置管理系统（单例+工厂）
    - 事件处理系统（观察者+命令）
    - 算法处理管道（策略+装饰器）
    - 对象构建系统（建造者+原型）
    """
    pass

# ============================================================================
# 基础设计模式接口
# ============================================================================

class PatternType(Enum):
    """设计模式类型枚举"""
    SINGLETON = "singleton"
    FACTORY = "factory"
    OBSERVER = "observer"
    COMMAND = "command"
    STRATEGY = "strategy"
    DECORATOR = "decorator"
    BUILDER = "builder"
    PROTOTYPE = "prototype"

class DesignPattern(ABC):
    """设计模式基类"""
    
    @abstractmethod
    def get_pattern_type(self) -> PatternType:
        """获取模式类型"""
        pass
    
    @abstractmethod
    def get_description(self) -> str:
        """获取模式描述"""
        pass

# ============================================================================
# 组合1: 单例+工厂模式 - 配置管理系统
# ============================================================================

class ConfigurationManager:
    """
    配置管理器 - 单例+工厂模式组合
    
    功能:
    - 单例确保全局唯一的配置管理器
    - 工厂模式创建不同类型的配置对象
    """
    
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        # TODO: 实现单例模式
        pass
    
    def __init__(self):
        if not hasattr(self, '_initialized'):
            self._config_factories = {}
            self._configs = {}
            self._initialized = True
    
    def register_config_factory(self, config_type: str, factory: Callable):
        """注册配置工厂"""
        # TODO: 实现工厂注册
        pass
    
    def create_config(self, config_type: str, **kwargs) -> Any:
        """创建配置对象"""
        # TODO: 实现配置对象创建
        pass
    
    def get_config(self, config_type: str) -> Any:
        """获取配置对象"""
        # TODO: 实现配置对象获取
        pass

class DatabaseConfig:
    """数据库配置"""
    def __init__(self, host: str, port: int, database: str):
        self.host = host
        self.port = port
        self.database = database
    
    def get_connection_string(self) -> str:
        return f"postgresql://{self.host}:{self.port}/{self.database}"

class RedisConfig:
    """Redis配置"""
    def __init__(self, host: str, port: int, db: int = 0):
        self.host = host
        self.port = port
        self.db = db
    
    def get_connection_string(self) -> str:
        return f"redis://{self.host}:{self.port}/{self.db}"

# ============================================================================
# 组合2: 观察者+命令模式 - 事件处理系统
# ============================================================================

class Command(ABC):
    """命令接口"""
    
    @abstractmethod
    def execute(self) -> Any:
        """执行命令"""
        pass
    
    @abstractmethod
    def undo(self) -> Any:
        """撤销命令"""
        pass

class Observer(ABC):
    """观察者接口"""
    
    @abstractmethod
    def update(self, event: str, data: Any) -> None:
        """处理事件"""
        pass

class EventProcessor:
    """
    事件处理器 - 观察者+命令模式组合
    
    功能:
    - 观察者模式处理事件订阅和通知
    - 命令模式封装事件处理逻辑
    """
    
    def __init__(self):
        self._observers: Dict[str, List[Observer]] = {}
        self._command_history: List[Command] = []
    
    def subscribe(self, event_type: str, observer: Observer):
        """订阅事件"""
        # TODO: 实现事件订阅
        pass
    
    def unsubscribe(self, event_type: str, observer: Observer):
        """取消订阅"""
        # TODO: 实现取消订阅
        pass
    
    def publish(self, event_type: str, data: Any):
        """发布事件"""
        # TODO: 实现事件发布
        pass
    
    def execute_command(self, command: Command):
        """执行命令"""
        # TODO: 实现命令执行
        pass
    
    def undo_last_command(self):
        """撤销最后一个命令"""
        # TODO: 实现命令撤销
        pass

class EmailNotificationCommand(Command):
    """邮件通知命令"""
    def __init__(self, recipient: str, message: str):
        self.recipient = recipient
        self.message = message
        self.sent = False
    
    def execute(self) -> Any:
        # TODO: 实现邮件发送
        pass
    
    def undo(self) -> Any:
        # TODO: 实现邮件撤销（记录撤销日志）
        pass

class LoggingObserver(Observer):
    """日志观察者"""
    def update(self, event: str, data: Any) -> None:
        # TODO: 实现日志记录
        pass

# ============================================================================
# 组合3: 策略+装饰器模式 - 算法处理管道
# ============================================================================

class ProcessingStrategy(ABC):
    """处理策略接口"""
    
    @abstractmethod
    def process(self, data: Any) -> Any:
        """处理数据"""
        pass

class ProcessingDecorator(ABC):
    """处理装饰器基类"""
    
    def __init__(self, strategy: ProcessingStrategy):
        self._strategy = strategy
    
    @abstractmethod
    def process(self, data: Any) -> Any:
        """装饰后的处理"""
        pass

class AlgorithmPipeline:
    """
    算法处理管道 - 策略+装饰器模式组合
    
    功能:
    - 策略模式选择不同的处理算法
    - 装饰器模式添加额外的处理功能
    """
    
    def __init__(self):
        self._strategies: Dict[str, ProcessingStrategy] = {}
        self._current_strategy: Optional[ProcessingStrategy] = None
    
    def register_strategy(self, name: str, strategy: ProcessingStrategy):
        """注册策略"""
        # TODO: 实现策略注册
        pass
    
    def set_strategy(self, name: str):
        """设置当前策略"""
        # TODO: 实现策略设置
        pass
    
    def add_decorator(self, decorator_class: type, **kwargs):
        """添加装饰器"""
        # TODO: 实现装饰器添加
        pass
    
    def process(self, data: Any) -> Any:
        """处理数据"""
        # TODO: 实现数据处理
        pass

class SortingStrategy(ProcessingStrategy):
    """排序策略"""
    def process(self, data: List) -> List:
        return sorted(data)

class FilteringStrategy(ProcessingStrategy):
    """过滤策略"""
    def __init__(self, condition: Callable):
        self.condition = condition
    
    def process(self, data: List) -> List:
        return [item for item in data if self.condition(item)]

class TimingDecorator(ProcessingDecorator):
    """计时装饰器"""
    def process(self, data: Any) -> Any:
        # TODO: 实现计时功能
        pass

class LoggingDecorator(ProcessingDecorator):
    """日志装饰器"""
    def process(self, data: Any) -> Any:
        # TODO: 实现日志功能
        pass

# ============================================================================
# 组合4: 建造者+原型模式 - 对象构建系统
# ============================================================================

class Prototype(ABC):
    """原型接口"""
    
    @abstractmethod
    def clone(self) -> 'Prototype':
        """克隆对象"""
        pass

class ComplexObject(Prototype):
    """复杂对象"""
    def __init__(self):
        self.properties: Dict[str, Any] = {}
        self.components: List[Any] = []
        self.metadata: Dict[str, Any] = {}
    
    def clone(self) -> 'ComplexObject':
        # TODO: 实现深度克隆
        pass
    
    def __str__(self):
        return f"ComplexObject(properties={self.properties}, components={len(self.components)})"

class ObjectBuilder:
    """对象建造者"""
    def __init__(self, prototype: Optional[ComplexObject] = None):
        if prototype:
            self._object = prototype.clone()
        else:
            self._object = ComplexObject()
    
    def add_property(self, key: str, value: Any) -> 'ObjectBuilder':
        """添加属性"""
        # TODO: 实现属性添加
        pass
    
    def add_component(self, component: Any) -> 'ObjectBuilder':
        """添加组件"""
        # TODO: 实现组件添加
        pass
    
    def set_metadata(self, metadata: Dict[str, Any]) -> 'ObjectBuilder':
        """设置元数据"""
        # TODO: 实现元数据设置
        pass
    
    def build(self) -> ComplexObject:
        """构建对象"""
        # TODO: 实现对象构建
        pass

class ObjectFactory:
    """
    对象工厂 - 建造者+原型模式组合
    
    功能:
    - 建造者模式构建复杂对象
    - 原型模式复用已有对象模板
    """
    
    def __init__(self):
        self._prototypes: Dict[str, ComplexObject] = {}
    
    def register_prototype(self, name: str, prototype: ComplexObject):
        """注册原型"""
        # TODO: 实现原型注册
        pass
    
    def create_builder(self, prototype_name: Optional[str] = None) -> ObjectBuilder:
        """创建建造者"""
        # TODO: 实现建造者创建
        pass
    
    def create_object(self, prototype_name: str, **properties) -> ComplexObject:
        """快速创建对象"""
        # TODO: 实现快速对象创建
        pass

# ============================================================================
# 模式组合器主类
# ============================================================================

class PatternCombiner:
    """
    设计模式组合器
    
    功能:
    - 管理和组合多种设计模式
    - 提供统一的接口访问组合功能
    - 支持模式的动态注册和发现
    """
    
    def __init__(self):
        self._patterns: Dict[str, Any] = {}
        self._combinations: Dict[str, List[str]] = {}
    
    def register_pattern(self, name: str, pattern_instance: Any):
        """注册设计模式实例"""
        # TODO: 实现模式注册
        pass
    
    def register_combination(self, name: str, pattern_names: List[str]):
        """注册模式组合"""
        # TODO: 实现组合注册
        pass
    
    def get_pattern(self, name: str) -> Any:
        """获取模式实例"""
        # TODO: 实现模式获取
        pass
    
    def get_combination(self, name: str) -> List[Any]:
        """获取模式组合"""
        # TODO: 实现组合获取
        pass
    
    def demonstrate_all_combinations(self):
        """演示所有模式组合"""
        # TODO: 实现组合演示
        pass

def demonstrate_pattern_combinations():
    """
    演示设计模式组合器的功能
    """
    print("=== 设计模式组合器演示 ===")
    
    combiner = PatternCombiner()
    
    # 演示配置管理系统（单例+工厂）
    print("\n=== 配置管理系统（单例+工厂）===")
    config_manager = ConfigurationManager()
    
    # 注册配置工厂
    config_manager.register_config_factory(
        "database", 
        lambda **kwargs: DatabaseConfig(**kwargs)
    )
    config_manager.register_config_factory(
        "redis", 
        lambda **kwargs: RedisConfig(**kwargs)
    )
    
    # 创建配置
    db_config = config_manager.create_config(
        "database", 
        host="localhost", 
        port=5432, 
        database="myapp"
    )
    print(f"数据库配置: {db_config.get_connection_string()}")
    
    # 演示事件处理系统（观察者+命令）
    print("\n=== 事件处理系统（观察者+命令）===")
    event_processor = EventProcessor()
    
    # 添加观察者
    logger = LoggingObserver()
    event_processor.subscribe("user_login", logger)
    
    # 发布事件
    event_processor.publish("user_login", {"user_id": 123, "timestamp": time.time()})
    
    # 执行命令
    email_cmd = EmailNotificationCommand("user@example.com", "欢迎登录")
    event_processor.execute_command(email_cmd)
    
    # 演示算法处理管道（策略+装饰器）
    print("\n=== 算法处理管道（策略+装饰器）===")
    pipeline = AlgorithmPipeline()
    
    # 注册策略
    pipeline.register_strategy("sort", SortingStrategy())
    pipeline.register_strategy("filter", FilteringStrategy(lambda x: x > 5))
    
    # 设置策略并添加装饰器
    pipeline.set_strategy("sort")
    pipeline.add_decorator(TimingDecorator)
    pipeline.add_decorator(LoggingDecorator)
    
    # 处理数据
    test_data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    result = pipeline.process(test_data)
    print(f"处理结果: {result}")
    
    # 演示对象构建系统（建造者+原型）
    print("\n=== 对象构建系统（建造者+原型）===")
    factory = ObjectFactory()
    
    # 创建原型
    base_prototype = ComplexObject()
    base_prototype.properties["type"] = "base"
    base_prototype.properties["version"] = "1.0"
    factory.register_prototype("base", base_prototype)
    
    # 使用建造者创建对象
    builder = factory.create_builder("base")
    complex_obj = (builder
                   .add_property("name", "测试对象")
                   .add_component("组件1")
                   .add_component("组件2")
                   .set_metadata({"created_at": time.time()})
                   .build())
    
    print(f"构建的对象: {complex_obj}")
    
    # 注册所有模式到组合器
    combiner.register_pattern("config_manager", config_manager)
    combiner.register_pattern("event_processor", event_processor)
    combiner.register_pattern("algorithm_pipeline", pipeline)
    combiner.register_pattern("object_factory", factory)
    
    # 注册组合
    combiner.register_combination("config_system", ["config_manager"])
    combiner.register_combination("event_system", ["event_processor"])
    combiner.register_combination("processing_system", ["algorithm_pipeline"])
    combiner.register_combination("object_system", ["object_factory"])
    
    print("\n=== 模式组合器注册完成 ===")
    print("所有设计模式组合已成功注册并演示")

if __name__ == "__main__":
    # 运行演示
    demonstrate_pattern_combinations()
    
    print("\n=== 设计模式组合最佳实践 ===")
    print("1. 理解每个模式的核心意图")
    print("2. 识别模式之间的协同点")
    print("3. 避免过度设计和模式滥用")
    print("4. 保持代码的简洁性和可读性")
    print("5. 根据实际需求选择合适的组合")
